<template>
  <div class="main-context">
    <img class="system-logo" src="@/assets/syslogo.png">
    <el-card class="login-card">
      <div class="card-header">
        <h2>密码登录</h2>
      </div>

      <el-form
        :model="formData"
        ref="formRef"
        label-width="0"
        :rules="formRules"
        @keyup.enter="submitForm"
      >
        <!-- 用户名输入 -->
        <el-form-item prop="name">
          <el-input
            v-model.trim="formData.name"
            :prefix-icon="User"
            placeholder="请输入账号"
            clearable
            size="large"
          />
        </el-form-item>

        <!-- 密码输入 -->
        <el-form-item prop="password">
          <el-input
            v-model.trim="formData.password"
            :prefix-icon="Lock"
            placeholder="请输入密码"
            show-password
            clearable
            size="large"
          />
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            @click="submitForm"
            style="width: 100%; margin-top: 10px; background-color:#ff6200; "
          >
            登录
          </el-button>
        </el-form-item>

        <!-- 辅助链接 -->
        <div class="helper-links">
          <router-link to="/" class="link-item">
            忘记密码？
          </router-link>
          <span class="divider">|</span>
          <router-link to="/register" class="link-item">
            立即注册
          </router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>

import { ref, reactive, onMounted } from 'vue'
import { User, Lock } from "@element-plus/icons-vue"
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import http from "@/utils/http.js"
import axios from 'axios'

const router = useRouter()
const route = useRoute()

// 表单数据
const formData = reactive({
  name: '',
  password: ''
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入用户名', trigger: ['blur', 'change'] }],
  password: [{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }]
}

// 表单引用
const formRef = ref(null)

// 检查是否有重定向参数
onMounted(() => {
  // 如果有重定向参数，显示提示信息
  if (route.query.redirect) {
    ElMessage.warning('请先登录后再访问该页面')
  }
})

// 提交表单
const submitForm = async () => {
  try {
    // 验证表单
    await formRef.value.validate()

    // 显示加载中提示
    const loading = ElMessage({
      message: '登录中...',
      type: 'info',
      duration: 0
    })

    // 发送登录请求
    const response = (await axios.post("/api/common/login", formData)).data
    console.log(response)
    
    // 关闭加载提示
    loading.close()
    
    if(response.code === 0){
      ElMessage.error("用户名或密码错误")
    } else {
      // 保存token
      localStorage.setItem("token", response.data.jwt)
      
      // 成功消息
      ElMessage.success("登录成功，正在跳转...")
      
      // 如果有重定向参数，跳转到该页面，否则根据用户类型跳转
      const redirectUrl = route.query.redirect || (response.data.type === "user" ? "/" : "/admin/admin")
      router.push(redirectUrl)
    }
  } catch (error) {
    console.error("Login error:", error)
    if (!error.response) {
      ElMessage.error("网络连接异常，请稍后重试")
    } else if (error.response.status === 401) {
      ElMessage.error("用户名或密码错误")
    } else if (error.response.status === 500) {
      ElMessage.error("服务器内部错误")
    } else {
      ElMessage.error("登录失败，请稍后重试")
    }
  }
}
</script>

<style scoped>
.main-context {
  height: 100vh;
  background: #f0eff2;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 60px;
}

.system-logo {
  width: 90px;
  margin-bottom: 200px;
  margin-left: -1100px;
  margin-top: -50px;
}

.login-card {
  width: 400px;
  border-radius: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
  margin-bottom: 30px;
}


.card-header h2 {
  color: #333;
  font-size: 24px;
  font-weight: 500;
}

.helper-links {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
}

.link-item {
  color: #409eff;
  text-decoration: none;
  transition: opacity 0.3s;
}

.link-item:hover {
  opacity: 0.8;
}

.divider {
  color: #dcdfe6;
  margin: 0 12px;
}

/* 调整输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 10px !important;
}

:deep(.el-select .el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset !important;
}
</style>